import axios from 'axios'
import { Message, Notification,MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})
const blackApi = ['/shop/order/splitOrder']
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log( getToken())
    if (getToken()) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    if(!config.url.includes('listChanne')){
      if ((config.method === 'post' || config.method === 'put' || config.responseType=='blob') && config.url!='/common/upload' && blackApi.includes(config.url)) {
        const requestObj = {
          url: config.url,
          data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
          time: new Date().getTime()
        }
        let sessionObj = sessionStorage.getItem('sessionObj')
        sessionObj =JSON.parse(sessionObj)
        if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
          sessionStorage.setItem('sessionObj',JSON.stringify(requestObj))
          // cache.session.setJSON('sessionObj', requestObj)
        } else {
          const s_url = sessionObj.url;                  // 请求地址
          const s_data = sessionObj.data;                // 请求数据
          const s_time = sessionObj.time;                // 请求时间
          const interval = 20000;                         // 间隔时间(ms)，小于此时间视为重复提交
          if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
            const message = '数据正在处理，请勿重复提交';
            console.warn(`[${s_url}]: ` + message)
            return Promise.reject(new Error(message))
          } else {
            // cache.session.setJSON('sessionObj', requestObj)
          sessionStorage.setItem('sessionObj',JSON.stringify(requestObj))

          }
        }
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(res => {
  if (res.data instanceof Blob) {
    return res
  }
  console.log(res)
  const code = res.data.code
  if (code === 401 || res.data.msg === 'Full authentication is required to access this resource') {
    MessageBox.alert(
      '登录状态已过期，请重新登录',
      '系统提示',
      {
        confirmButtonText: '确定'
      }
    ).then(() => {
      store.dispatch('user/logout').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    }).catch(() => { })
  }
  if (code !== 200) {

    // Notification.error({
    //   title: res.data.msg
    // })
    Message({
      message: res.data.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject('error')
  } else {
    return res.data
  }
}, error => {
  Message().close()

  console.log('err' + error)
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
